<template>
  <div class="personal-info-container">
    <!-- 个人信息展示卡片 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="editDialogVisible = true">编辑信息</el-button>
        </div>
      </template>

      <div class="info-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户名">{{ admin.username || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ admin.name || '未设置' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- 修改密码卡片 -->
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword">确认修改</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 编辑信息对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑个人信息" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const user = ref()
const admin = ref({})

// 密码表单
const passwordFormRef = ref(null)
const passwordForm = ref({
  newPassword: '',
  confirmPassword: ''
})

// 编辑表单
const editFormRef = ref(null)
const editDialogVisible = ref(false)
const editForm = ref({
  username: '',
  name: ''
})

// 表单验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const editRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
  ]
}

// 获取管理员信息
const getAdminInfo = () => {
  // 直接从sessionStorage获取用户信息
  const userData = JSON.parse(sessionStorage.getItem("user"))
  if (userData) {
    admin.value = {
      username: userData.username,
      name: userData.name,
      id: userData.id
    }
    editForm.value = {
      username: userData.username,
      name: userData.name
    }
  }
}

// 修改密码
const handleChangePassword = () => {
  passwordFormRef.value.validate(valid => {
    if (valid) {
      axios.get('/admin/updateAdminDetails', {
        params: {
          id: admin.value.id,
          Npassword: passwordForm.value.newPassword

        }
      })
          .then(res => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.msg)
              resetPasswordForm()
              // 更新sessionStorage中的用户信息
              const updatedUser = {...JSON.parse(sessionStorage.getItem("user"))}
              sessionStorage.setItem("user", JSON.stringify(updatedUser))
            } else {
              ElMessage.error(res.data.msg)
            }
          })
          .catch(error => {
            ElMessage.error('修改密码失败')
            console.error('修改密码失败:', error)
          })
    }
  })
}

// 提交编辑表单
const submitEditForm = () => {
  editFormRef.value.validate(valid => {
    if (valid) {
      axios.get('/admin/updateAdminDetails', {
        params: {
          id: admin.value.id,
          name: editForm.value.name,
          username: admin.value.username,
          Opassword: passwordForm.value.newPassword,
          Npassword: passwordForm.value.newPassword
        }
      })
          .then(res => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.msg)
              // 更新sessionStorage中的用户信息
              const updatedUser = {...JSON.parse(sessionStorage.getItem("user"))}
              updatedUser.name = editForm.value.name
              sessionStorage.setItem("user", JSON.stringify(updatedUser))
              getAdminInfo() // 刷新数据
              editDialogVisible.value = false
            } else {
              ElMessage.error(res.data.msg)
            }
          })
          .catch(error => {
            ElMessage.error('更新个人信息失败')
            console.error('更新个人信息失败:', error)
          })
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 初始化加载
onMounted(() => {
  getAdminInfo()
})
</script>

<style scoped>
.personal-info-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.info-card, .password-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-content {
  padding: 10px;
}

:deep(.el-descriptions__body) {
  background-color: #fafafa;
}

:deep(.el-descriptions__label) {
  width: 100px;
  font-weight: bold;
}

.operation-area {
  margin-top: 20px;
  text-align: right;
}
</style>